<?php

namespace App\Http\Controllers;

use App\Models\Expert;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ExpertController extends Controller
{
    public function index(){
        $oExpert=Expert::orderby('id')->paginate(5);
        return view('admin.expert-list')
            ->with('oExpert',$oExpert);
    }
    public function create(){
        return view('admin.add-expert');
    }
    public function store(Request $request){
        $data=$request->input();
        $rules=[
            'name'=>'required|min:3|max:30|alpha_num',
            'department'=>'required',
            'position'=>'required',
            'duties'=>'required',
            'hospital'=>'required',
            'profile'=>'required',
            'education'=>'required',
        ];
        $messages=[
            'name.required'=>'用户姓名不能为空，必须填写',
            'name.min'=>'用户姓名至少:min个字符',
            'name.max'=>'用户姓名不得多于:max个字符',
            'department.required'=>'科室不能为空',
            'position.required'=>'职称不能为空',
            'duties.required'=>'职务不能为空',
            'hospital.required'=>'医院不能为空',
            'profile.required'=>'简介不能为空',
            'education.required'=>'受教育层面不能为空',

        ];
        $validate=Validator::make($data,$rules,$messages);
        $validate->validate();

        $expert=$request->input();
        if($request->hasFile('thumb')){
            $file=$request->file('thumb');
            $ext=$file->extension();
            $filename=time().".".$ext;
            $file->move(public_path()."/upload",$filename);
            $expert["thumb"]='/upload/'.$filename;
        }else{
            $expert["thumb"]='/res/test_images/e3.jpg';
        }
        Expert::create($expert);
        return redirect('/adm/expert');
    }
    public function edit($id){
        $expert=Expert::find($id);
        return view('admin.edit-expert')
            ->with('oExpert',$expert);
        }
    public function update(Request $request, $id){

        $expert=Expert::find($id);
        $aexpert=$request->input();
        if($request->hasFile('thumb')){
            $file=$request->file('thumb');
            $ext=$file->extension();
            $filename=time().".".$ext;
            $file->move(public_path()."/upload",$filename);
            $aexpert["thumb"]='/upload/'.$filename;

        }else{
            $aexpert["thumb"]=$expert->thumb;
        }
        $expert->update($aexpert);
        return redirect('/adm/expert');
    }
    public function destroy($id){
        $expert=Expert::find($id);
        $expert->delete();
        return redirect('/adm/expert');
    }
}
